import os
import sys
import logging
import cv2
import time
import traceback

from multiprocessing import Process, Queue

from nodes.Node import Node
from nodes.SourceNode import SourceNode
from nodes.ElementNode import ElementNode
from nodes.VideoListSourceNode import VideoListSourceNode

#from utils import *

class FishVideoListSourceNode(VideoListSourceNode):

    def __init__(self, name="FishVideoListSourceNode", parent=None, videoDir="VideoDir"):
        super(FishVideoListSourceNode,self).__init__()
        SourceNode.__init__(self, name,parent,videoDir,SourceNode.SOURCE_TYPE_MULTI_CHANNEL_VIDEO)

    def closeAction(self):
        print("+++++++++++++++++++++++++++++++++________++++++++++++++++++++++++++++++++++++++++++")
        print("---------------------------------Close Action -------------------------------------")

    #def open(self,idx):
    #    self._capture = cv2.VideoCapture(self._videoList[idx])

    #    dict =  {}
    #    dict["VideoID"]=idx
    #    dict["VideoFile"]=self._videoList[idx]

    #    StoreGlobalDict(SHM_VIDEO_NAME, dict)

    #    return self._capture.isOpened()

    def run(self):
        fileIdx = 0
        self.setStatus(Node.NODE_STATUS_RUNNING)
        while(True):
            if fileIdx >=  len(self._videoList):
                break

            self.open(fileIdx)

            frameIndex = 0

            while(self._capture.isOpened()):

                #logging.info('VideoListCxSourceNode: Node is running...')

                if self._stopFlag:
                    break

                if self._pauseFlag:
                    continue

                (grabbed, frame) = self._capture.read()

                if not grabbed:
                    break

                if frame is not None:

                    #height, width, channels = frame.shape
                    frameIndex += 1

                    frame = cv2.resize(frame, (960, 540))

                    self.passFrame([frame, fileIdx, frameIndex])

                    logging.info("FishVideoListSourceNode: " + str(frameIndex) +  " Frames pushed into frame pool.")

                    time.sleep(0.02)

            fileIdx += 1

            self.close()

        self.setStatus(Node.NODE_STATUS_EXITED)
        logging.error("+++++++++++++++++++ FishVideListSourceNode is completed. ++++++++++++++++++++++++")
